//
//  GuestManagerViewController.m
//  QRMaster
//
//  Created by myApple on 15/4/13.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "GuestManagerViewController.h"
#import "RequestNetWork.h"
#import "GuestModel.h"
#import "PromptInfoView.h"
#import "GuestInfoView.h"
#import "Reachability.h"
#import "SetGuestDateTimeViewController.h"
#import "StartPageController.h"
#import "UIImageView+WebCache.h"
#import "BackBtn.h"
#import "DeleteView.h"
#import "GuestInfoCell.h"
#import "GuestLogic.h"
#import "GroupGuestLogic.h"
#import "EditGuestInfoController.h"
#import "EditCertificateController.h"
#import "InternationalControl.h"

@interface GuestManagerViewController ()<UIActionSheetDelegate,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
{
    UILabel * nameLabel;
    UITableView * guestInfoTabelView;
    NSArray * titleNameArray;
    UILabel * guestNameLabel;
    UIImageView * sexImageView;
    UIView * firstSectionView;
    UIButton * moreViewBtn;//右上角的button
    UIView * backView;//透明的遮罩层
    UIView * backListView;//下拉黑色view
    UIButton * backBtn;//返回键
}

@end

@implementation GuestManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"detailInfo", nil);
    titleNameArray = @[NSLocalizedString(@"telePhone", nil),NSLocalizedString(@"email", nil),NSLocalizedString(@"certificate", nil),NSLocalizedString(@"openRoomPower", nil),NSLocalizedString(@"setOpenTime", nil)];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    [self prepareBtnView];
    [self prepareTableView];
    [self prepareFirstSectionView];
    [self prepareBackView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    moreViewBtn.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    moreViewBtn.hidden = YES;
    backBtn.hidden = YES;
}

-(void)prepareTableView
{
    float x = 0;
    float y = 0;
    float height = UI_SCREEN_HEIGHT - 64 - y;
    float width = UI_SCREEN_WIDTH;
    
    guestInfoTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStyleGrouped];
    guestInfoTabelView.backgroundColor = UIColorFromRGB(0xebebeb);
    guestInfoTabelView.delegate = self;
    guestInfoTabelView.dataSource = self;
    guestInfoTabelView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:guestInfoTabelView];
}

-(void)prepareFirstSectionView
{
    float x = 0;
    float y = 0;
    float height = 78;
    float width = UI_SCREEN_WIDTH;
    firstSectionView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    
    x = 22;
    y = (78 - 48) / 2.0;
    height = 48;
    width = 48;
    UIImageView * headerImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [headerImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",YSBHEADERIMGURL,_model.headUrl]] placeholderImage:[UIImage imageNamed:@"ic_加载头像212"]];
    headerImageView.layer.cornerRadius = 24;
    headerImageView.layer.masksToBounds = YES;
    [firstSectionView addSubview:headerImageView];
    
    x = 94;
    width = UI_SCREEN_WIDTH - x - 40;
    height = 20;
    y = (78 - 20)/2.0;
    nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    nameLabel.font = [UIFont systemFontOfSize:16.0];
    nameLabel.textColor = UIColorFromRGB(0x333333);
    nameLabel.text = _model.guestName;
    [firstSectionView addSubview:nameLabel];
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],};
    CGSize textSize = [_model.guestName boundingRectWithSize:CGSizeMake(500, 20) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    x += textSize.width + 10;
    y = (78 - 14)/2.0;
    height = 14;
    width = 12;
    sexImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    if ([_model.sex isEqualToString:@"1"]) {
        sexImageView.image = [UIImage imageNamed:@"male"];
    }
    else if ([_model.sex isEqualToString:@"0"])
    {
        sexImageView.image = [UIImage imageNamed:@"female"];
    }
    [firstSectionView addSubview:sexImageView];
    
}

#pragma mark ----------- 导航栏上的btn
-(void)prepareBtnView
{
    float x = UI_SCREEN_WIDTH - 40;
    float y = 0;
    float width = 40;
    float height = 40;
    moreViewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    moreViewBtn.frame = CGRectMake(x, y, width, height);
    [moreViewBtn addTarget:self action:@selector(showOrHiddenMoreView) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:moreViewBtn];
    
    x = 20;
    width = 4;
    height = 18;
    y = 11;
    UIImageView * moreImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    moreImageView.image = [UIImage imageNamed:@"moreInfo"];
    [moreViewBtn addSubview:moreImageView];
    
    x = 0;
    y = 0;
    width = 56;
    height = 40;
//    UIButton * btn = [BackBtn initWithFrame:CGRectMake(x, y, width, height) withImage:@"navigationBack"];
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
//    self.navigationController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    [backBtn addTarget:self action:@selector(guestInfoBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

-(void)showOrHiddenMoreView
{
    backView.hidden = !backView.hidden;
}

-(void)setModel:(GuestModel *)model
{
    _model = model;
}

#pragma mark ------- 准备右上角的更多view
-(void)prepareBackView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT;
    backView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
    backView.userInteractionEnabled = YES;
    backView.hidden = YES;
    [self.view addSubview:backView];
    UITapGestureRecognizer * tapAllBackView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenView)];
    tapAllBackView.delegate = self;
    [backView addGestureRecognizer:tapAllBackView];
    
    x = backView.frame.size.width - 22;
    y = 4;
    width = 11;
    height = 6;
    UIImageView * triangleView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    triangleView.image = [UIImage imageNamed:@"triangle"];
    triangleView.backgroundColor = [UIColor clearColor];
    [backView addSubview:triangleView];
    
    x = UI_SCREEN_WIDTH - 134;
    y = 10;
    width = 128;
    height = 39 * 2;
    if ([[InternationalControl userLanguage]isEqualToString:@"en"]) {
        x = UI_SCREEN_WIDTH / 2.0 - 26;
        width = UI_SCREEN_WIDTH / 2.0 + 20;
    }
    backListView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    backListView.backgroundColor = [UIColor blackColor];
    backListView.layer.cornerRadius = 2;
    [backView addSubview:backListView];
    
    x = 0;
    y = 0;
    height = 39;
    DeleteView * firstView = [[DeleteView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    firstView.imageString = @"edit";
    firstView.titleString = NSLocalizedString(@"modifyGuestInfo", nil);
    UITapGestureRecognizer * firstTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(editTap)];
    firstTap.delegate = self;
    [firstView addGestureRecognizer:firstTap];
    [backListView addSubview:firstView];
    
    x = 16;
    y = 39;
    width -= 2 * x;
    height = 0.5;
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    lineView.backgroundColor = RGBA(81, 81, 81, 1);
    [backListView addSubview:lineView];
    
    x = 0;
    y = 39.5;
    width = firstView.frame.size.width;
    height = 39;
    DeleteView * secondeView = [[DeleteView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    secondeView.imageString = @"delete";
    secondeView.titleString = NSLocalizedString(@"delete", nil);
    UITapGestureRecognizer * secondeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteTap)];
    secondeTap.delegate = self;
    [secondeView addGestureRecognizer:secondeTap];
    [backListView addSubview:secondeView];
}

-(void)hiddenView
{
    backView.hidden = YES;
}

#pragma mark --------- 编辑操作
-(void)editTap
{
    [self hiddenView];
    EditGuestInfoController * esfc = [[EditGuestInfoController alloc]initWithModel:_model];
    esfc.groupId = _groupId;
    esfc.editGuestBlock = ^(GuestModel * model)
    {
        nameLabel.text = model.guestName;
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],};
        CGSize textSize = [_model.guestName boundingRectWithSize:CGSizeMake(500, 20) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
        sexImageView.frame = CGRectMake(nameLabel.frame.origin.x + textSize.width + 10 , sexImageView.frame.origin.y, sexImageView.frame.size.width, sexImageView.frame.size.height);
    };
    [self.navigationController pushViewController:esfc animated:YES];
}

#pragma mark --------- 删除操作
-(void)deleteTap
{
    [self hiddenView];
    UIActionSheet * quitAcitonSheet = [[UIActionSheet alloc]initWithTitle:NSLocalizedString(@"deleteOrNot", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"not", nil) destructiveButtonTitle:NSLocalizedString(@"yes", nil) otherButtonTitles:nil];
    [quitAcitonSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self makeSureDelete];
    }
}

#pragma mark ==== 点击删除传过来的信息
-(void)makeSureDelete
{
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDicts = [[NSMutableDictionary alloc]init];
    NSString * urlString = @"";
    [postDicts setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDicts setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDicts setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    if (_groupId) {
        urlString = DELETEGROUPCLIENT;
        [postDicts setValue: _groupId forKey:@"groupId"];
        [postDicts setValue: _model.guestid forKey:@"clientId"];
        if([self getTimestamp:_groupId] != nil)
        {
            [postDicts setValue:[self getTimestamp:_groupId] forKey:@"timestamp"];
        }
        else
        {
            [postDicts setValue:@"" forKey:@"timestamp"];
        }    }
    else
    {
        urlString = DELETEGUEST;
        [postDicts setValue:_model.guestid forKey:@"memberIds"];
        if([self getTimestamp:[QRSingleton sharedQRSingleton].communityId timeKey:@"customer_timestamp"] != nil)
        {
            [postDicts setValue:[self getTimestamp:[QRSingleton sharedQRSingleton].communityId timeKey:@"customer_timestamp"] forKey:@"timestamp"];
        }
        else
        {
            [postDicts setValue:@"" forKey:@"timestamp"];
        }
    }
    __weak GuestManagerViewController * guestSelf = self;
    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(urlString) params:postDicts block:^(id downLoadData, id error)
     {
         [guestSelf stopWaiting];
         if ([downLoadData objectForKey:@"cache"] != nil) {
             if([@"0" isEqualToString:[NSString stringWithFormat:@"%@",[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]]]==YES)
             {
                 if (_groupId) {
                     [self updateTimestamp:_groupId timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                     GroupGuestLogic * groupLogic = [[GroupGuestLogic alloc]init];
                     [groupLogic deleteGroupGuestInfoByGroupId:_groupId];
                 }
                 else
                 {
                     [self updateTimestamp:[QRSingleton sharedQRSingleton].communityId timeKey:@"customer_timestamp" timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                     GuestLogic * guestLogic = [[GuestLogic alloc]init];
                     [guestLogic deleteGuestInfo:_model.guestid withCommunityId:[QRSingleton sharedQRSingleton].communityId ];
                 }
                 [guestSelf guestInfoBack];
             }
         }
         else
         {
             [PromptInfoView showMessage:[error objectForKey:@"info"]];
             if ([[error objectForKey:@"status"]integerValue] == 334)
             {
                //用户在别处被删除了
                 [guestSelf guestInfoBack];
                 if (_groupId) {
                     GroupGuestLogic * groupLogic = [[GroupGuestLogic alloc]init];
                     [groupLogic deleteGroupGuestInfo:_groupId groupGuest:_model.guestid];
                 }
                 else
                 {
                     GuestLogic * guestLogic = [[GuestLogic alloc]init];
                     [guestLogic deleteGuestInfo:_model.guestid withCommunityId:[QRSingleton sharedQRSingleton].communityId ];
                 }
             }
         }
     }];
    
}


#pragma mark --------- tableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 2) {
        return 1;
    }
    else
    {
        return 2;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 78.0;
    }
    else
        return 56;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 16.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * identityId = @"cell";
    GuestInfoCell * cell = [tableView dequeueReusableCellWithIdentifier:identityId];
    if (!cell) {
        cell = [[GuestInfoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identityId];
    }
    if (indexPath.section == 0) {
        [cell addSubview:firstSectionView];
    }
    else
    {
        if (indexPath.section == 1)
        {
            cell.titleNameString = titleNameArray[indexPath.row];
            if (indexPath.row == 0) {
                cell.contentString = _model.telePhone;
                cell.contentColor = UIColorFromRGB(0x00aff0);
            }
            else
            {
                cell.contentString = _model.email;
                cell.contentColor = UIColorFromRGB(0x333333);
            }
        }
        else if (indexPath.section == 2)
        {
            cell.titleNameString = titleNameArray[indexPath.section + indexPath.row];
            if (_model.certificaties.length <= 2) {
                cell.contentString = _model.certificaties;
            }
            else
            {
                NSRange range = NSMakeRange(1, _model.certificaties.length - 2);
                NSString * starString  = @"******************************";
                NSString * replace = [starString substringToIndex:(_model.certificaties.length - 2)];
                cell.contentString = [_model.certificaties stringByReplacingCharactersInRange:range withString:replace];
            }
            cell.contentColor = UIColorFromRGB(0x727272);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else
        {
            if (indexPath.section == 3) {
                cell.titleNameString = titleNameArray[indexPath.section + indexPath.row];
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
             [self callPhone];
        }
    }
    else if (indexPath.section == 2)
    {
        EditCertificateController * ecc = [[EditCertificateController alloc]initWithModel:_model];
        ecc.editCertificateBlock = ^(NSString * certificateString)
        {
            _model.certificaties = certificateString;
            [guestInfoTabelView reloadData];
        };
        [self.navigationController pushViewController:ecc animated:YES];
    }
    else if (indexPath.section == 3)
    {
        if (indexPath.row == 0) {
            RoomSeclectViewController * rsvc = [[RoomSeclectViewController alloc]init];
            rsvc.communityid = _communityid;
            rsvc.memberid = _model.guestid;
            if ([QRSingleton sharedQRSingleton].roleIndex == 5) {
                rsvc.guestOrStaff = @"2";
                rsvc.groupId = _groupId;
                rsvc.areaCode = _model.areaCode;
                rsvc.mobile = _model.telePhone;
                rsvc.email = _model.email;
            }
            else
                rsvc.guestOrStaff = @"0";
            [self.navigationController pushViewController:rsvc animated:YES];
        }
        else
        {
            SetGuestDateTimeViewController * sgdtvc = [[SetGuestDateTimeViewController alloc]init];
            sgdtvc.guestId = _model.guestid;
            sgdtvc.community = _communityid;
            [self.navigationController pushViewController:sgdtvc animated:YES];
        }
    }
}

#pragma mark ---------- 系统打电话
-(void)callPhone
{
    NSString * callString = nil;
    if (![_model.areaCode isEqualToString:[QRSingleton sharedQRSingleton].currentAreaCodeString]) {
        callString = [NSString stringWithFormat:@"+%@-%@",_model.areaCode,_model.telePhone];
    }
    else
    {
        callString = _model.telePhone;
    }
    NSString *telUrl = [NSString stringWithFormat:@"telprompt://%@",callString];
    NSURL *url = [NSURL URLWithString:telUrl];
    [[UIApplication sharedApplication] openURL:url];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//通过groupId来查询到时间戳
-(NSString *)getTimestamp:(NSString *)groupId
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    return [groupGuestLogic queryGroupGuestTime:groupId];
}


//通过groupId来更新时间戳
-(void)updateTimestamp:(NSString *)groupId timeKeyValue:(NSString *)timeKeyValue
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    [groupGuestLogic updateGroupGuestTime:groupId keyValue:timeKeyValue];
}

-(void)guestInfoBack
{
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    
}


@end
